﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using HIWSystem.Models;
using HIWSystem.Helpers;
using HIWSystem.Common;
using System.Windows;

namespace HIWSystem.ViewModel
{
    [MetadataType(typeof(AddEmployeeViewModel))]
    public class UpdateEmployeeViewModel :ViewModelBase,IDataErrorInfo
    {
        
        public UpdateEmployeeViewModel()
        {
            Messenger.Default.Register<EmployeesEntity>(this, "UpdateEmployeeInfo", ReceiveAndShowEmployeeInfo);
        }

        #region 属性
        /// <summary>
        /// 表单验证错误集合
        /// </summary>
        private Dictionary<String, String> dataErrors = new Dictionary<String, String>();
        private string userNo;
        /// <summary>
        /// 工号
        /// </summary>
        //[Required]
        //[StringLength(maximumLength:8,MinimumLength =8,ErrorMessage ="工号的长度为8位")]
        [RegularExpression(@"^(HIW|TEM|TS)\d{5}$", ErrorMessage = "输入的工号格式不正确,正确的格式(HIW|TEM|TS+5位数字)")]
        public string UserNo
        {
            get { return userNo; }
            set { userNo = value; this.RaisePropertyChanged(() => UserNo); }
        }
        private string nameCn;
        /// <summary>
        /// 中文名
        /// </summary>
        [Required]
        public string NameCn
        {
            get { return nameCn; }
            set { nameCn = value; this.RaisePropertyChanged(() => NameCn); }
        }
        private string nameEn;
        /// <summary>
        /// 英文名
        /// </summary>
        [RegularExpression(@"[a-zA-Z]*")]
        public string NameEn
        {
            get { return nameEn; }
            set { nameEn = value; this.RaisePropertyChanged(() => NameEn); }
        }
        private string password;
        /// <summary>
        /// 密码
        /// </summary>
        [Required]
        public string Password
        {
            get { return password; }
            set { password = value; this.RaisePropertyChanged(() => Password); }
        }
        private string sex;
        /// <summary>
        /// 性别
        /// </summary>
        [RegularExpression("(男|女)", ErrorMessage = "性别只能是男或者女")]
        public string Sex
        {
            get { return sex; }
            set { sex = value; this.RaisePropertyChanged(() => Sex); }
        }

        private string departmentNo;
        /// <summary>
        /// 部门编号
        /// </summary>
        public string DepartmentNo
        {
            get { return departmentNo; }
            set { departmentNo = value; this.RaisePropertyChanged(() => DepartmentNo); }
        }
        private string telephone;
        /// <summary>
        /// 电话号码
        /// </summary>
        [RegularExpression(@"^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$")]
        public string Telephone
        {
            get { return telephone; }
            set { telephone = value; this.RaisePropertyChanged(() => Telephone); }
        }
        //private String userEmail;
        ///// <summary>
        ///// 用户邮件
        ///// </summary>
        //[Required]
        //[StringLength(100, MinimumLength = 2)]
        //[RegularExpression("^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@(\\w+\\.)+\\w{2,5})\\s*$", ErrorMessage = "请填写正确的邮箱地址.")]
        //public String UserEmail
        //{
        //    get { return userEmail; }
        //    set { userEmail = value; }
        //}
        private string address;
        /// <summary>
        /// 地址
        /// </summary>
        public string Address
        {
            get { return address; }
            set { address = value; this.RaisePropertyChanged(() => Address); }
        }
        private string oldUserNo;
        /// <summary>
        /// 旧工号
        /// </summary>
        public string OldUserNo
        {
            get { return oldUserNo; }
            set { oldUserNo = value; this.RaisePropertyChanged(() => OldUserNo); }
        }
        private string access;
        /// <summary>
        /// 权限
        /// </summary>
        [RegularExpression(@"^[A-Z]{2}(\|[A-Z]{2})*$", ErrorMessage = "权限的格式不正确(例如:AB|AC|AD)")]
        public string Access
        {
            get { return access; }
            set { access = value; this.RaisePropertyChanged(() => Access); }
        }
        #endregion

        #region 命令
        private RelayCommand searchLevelCmd;

        public RelayCommand SearchLevelCmd
        {
            get
            {
                if (searchLevelCmd == null)
                {
                    searchLevelCmd = new RelayCommand(() => {
                        ViewManager.Show("MenuLevel");
                    });
                }
                return searchLevelCmd;
            }
            set { searchLevelCmd = value; }
        }
        private RelayCommand updateCmd;
        /// <summary>
        /// 更新
        /// </summary>
        public RelayCommand UpdateCmd
        {
            get 
            {
                if (updateCmd==null)
                {
                    updateCmd = new RelayCommand(Update);
                }
                return updateCmd; 
            }
            set { updateCmd = value; }
        }
        //private RelayCommand windowClosingCommand;

        //public RelayCommand WindowClosingCommand
        //{
        //    get
        //    {
        //        if (windowClosingCommand == null)
        //        {
        //            windowClosingCommand = new RelayCommand(() => { Messenger.Default.Unregister(this); });
        //        }
        //        return windowClosingCommand;
        //    }
        //    set { windowClosingCommand = value; }
        //}

        #endregion

        #region 方法
        private void ReceiveAndShowEmployeeInfo(EmployeesEntity employees)
        {
            if (employees!=null)
            {
                this.UserNo = employees.UserNo;
                this.NameCn = employees.NameCn;
                this.NameEn = employees.NameEn;
                this.Password = MD5Helper.MD5Decrypt(employees.Password);
                this.Sex = employees.Sex;
                this.DepartmentNo = employees.DepartmentNo;
                this.Telephone = employees.Telephone;
                this.Address = employees.Address;
                this.OldUserNo = employees.OldUserNo;
                this.Access = employees.Access;

            }

        }
        /// <summary>
        /// 更新员工信息
        /// </summary>
        private void Update()
        {
            if (dataErrors.Count == 0)
            {
                string retMsg = string.Empty;
                EmployeesEntity employeesEntity = new EmployeesEntity()
                {
                    UserNo = this.UserNo.ToUpper() ?? "",
                    NameCn = this.NameCn ?? "",
                    NameEn = this.NameEn ?? "",
                    Password = MD5Helper.MD5Encrypt(this.Password),
                    Sex = this.Sex ?? "",
                    DepartmentNo = this.DepartmentNo ?? "",
                    Telephone = this.Telephone ?? "",
                    Address = this.Address ?? "",
                    OldUserNo = this.OldUserNo ?? "",
                    Access = this.Access ?? ""
                };
                retMsg = BusinessProcess.UpdateEmployeeInfo(employeesEntity);
                if (retMsg.Split('|')[0] == "Y")
                {
                    MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
                    Messenger.Default.Send("更新完成", "CompleteEmployeeUpdate");
                    //ViewManager.Close("UpdateEmployee");
                }
                else
                {
                    MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            } /*MessageBox.Show("验证通过！");*/
            else
                MessageBox.Show("信息输入有误！", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        public string this[string columnName]
        {
            get
            {
                ValidationContext vc = new ValidationContext(this, null, null);
                vc.MemberName = columnName;
                var res = new List<ValidationResult>();
                var result = Validator.TryValidateProperty(this.GetType().GetProperty(columnName).GetValue(this, null), vc, res);
                if (res.Count > 0)
                {
                    AddDic(dataErrors, vc.MemberName);
                    return string.Join(Environment.NewLine, res.Select(r => r.ErrorMessage).ToArray());
                }
                RemoveDic(dataErrors, vc.MemberName);
                return null;
            }
        }

        public string Error
        {
            get
            {
                return null;
            }
        }
        /// <summary>
        /// 移除字典
        /// </summary>
        /// <param name="dics"></param>
        /// <param name="dicKey"></param>
        private void RemoveDic(Dictionary<String, String> dics, String dicKey)
        {
            dics.Remove(dicKey);
        }

        /// <summary>
        /// 添加字典
        /// </summary>
        /// <param name="dics"></param>
        /// <param name="dicKey"></param>
        private void AddDic(Dictionary<String, String> dics, String dicKey)
        {
            if (!dics.ContainsKey(dicKey)) dics.Add(dicKey, "");
        }
        #endregion
    }
}
